package com.hmjk.health.background.data;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.text.format.Time;
import android.util.Log;

import com.hmjk.health.HealthApp;
import com.hmjk.health.background.DataManager;
import com.hmjk.health.background.DatabaseHelper;
import com.hmjk.health.background.NetService;

import com.hmjk.health.util.DEV_SET;

public class DeviceSettingsUpdated extends DataUpdated{
	private static String TAG = DeviceSettingsUpdated.class.getSimpleName();
	private ArrayList<String> mTIDArray = new ArrayList<String>();
	private int index = 0;
	private boolean working = false;
	private boolean doSingle = false;
	
	private void logd(String info){
		Log.d(TAG, info);
	}
	
	public DeviceSettingsUpdated(HealthApp app, DataManager dm) {
		super(app, dm);
		//UPDATE_TIME = 10 * 60 * 1000;
	}

	@Override
	public void setUserData(Object data) {
		logd("setUserData");
		String[] in = (String[]) data;
		if((in != null) && (in.length == 1) && (in[0] != null) && in[0].equalsIgnoreCase("reset_time")){
			reqTime = 0;
			return;
		}
		mTIDArray.clear();
		index = 0;
		reqTime = 0;
		if((in == null) || (in.length == 0))
			return;
		
		for(String tid:in){
			mTIDArray.add(tid);
		}
	}

	@Override
	public long delay() { //不自动获取
		// TODO Auto-generated method stub
		return -1;
	}

	@Override
	public boolean grab() {
		// TODO Auto-generated method stub
		return false;
	}
	
	private void doNextRequest(){
		if(doSingle){
			doSingle = false;
			working = false;
			return;
		}
		
		String uid = mApp.getUID();
		if(uid != null){
			int size = mTIDArray.size();
			if(index < size){
				doRequest(uid);
				index ++;
			}else{
				working = false;
			}
		}else{
			working = false;
		}
	}
	
	private void doRequest(String uid){
		doSingle = false;
		String tid = mTIDArray.get(index);
		Intent si = new Intent(NetService.GET_DATA_ACTION);
		si.putExtra("sub_act", NetService.CHECK_DEVICE_SETTINGS);
		si.putExtra("uid", uid);
		si.putExtra("tid", tid);
			
		Time t = new Time();
		t.setToNow();
		String stamp = "CHECK_DEVICE_SETTINGS" + t.toString(); 
		si.putExtra("stamp",stamp);
		mApp.addNetHandler(stamp,mDm.getBackGroundHandler());
		mApp.startService(si);
	}
	
	private void doSingleRequest(String uid, String tid){
		doSingle = true;

		Intent si = new Intent(NetService.GET_DATA_ACTION);
		si.putExtra("sub_act", NetService.CHECK_DEVICE_SETTINGS);
		si.putExtra("uid", uid);
		si.putExtra("tid", tid);
			
		Time t = new Time();
		t.setToNow();
		String stamp = "CHECK_DEVICE_SETTINGS" + t.toString(); 
		si.putExtra("stamp",stamp);
		mApp.addNetHandler(stamp,mDm.getBackGroundHandler());
		mApp.startService(si);
	}
	
	@Override
	public boolean grabByUserWithSingleArgs(Object args){
		if(args == null)
			return false;
		
		String argString = (String)args;
		if(argString.trim().isEmpty())
			return false;
		
		String uid = mApp.getUID();
		logd("grabByUserWithSingleArgs uid="+uid);
		if(uid == null)
			return false;
		
		if(working){
			logd("grabByUserWithSingleArgs working");
			return false;
		}
				
		long curMs = System.currentTimeMillis();
		logd("grabByUserWithSingleArgs curMs="+curMs+" reqTime="+reqTime);
		if((curMs - reqTime) > MIN_QUERY_DUR * 1000){
			working = true;
			doSingleRequest(uid, argString);
			reqTime = curMs;
			logd("grabByUserWithSingleArgs req sent!");
			return true;
		}
		return false;
	}

	@Override
	public boolean grabByUser() {
		String uid = mApp.getUID();
		logd("grabByUser uid="+uid);
		if(uid == null)
			return false;
		
		if(working){
			logd("grabByUser working now");
			return false;
		}
		if(mTIDArray.size() == 0){
			logd("grabByUser not tid specified to be check");
			return false;
		}
		
		long curMs = System.currentTimeMillis();
		logd("grabByUser curMs="+curMs+" reqTime="+reqTime);
		if((curMs - reqTime) > MIN_QUERY_DUR * 1000){
			working = true;
			doRequest(uid);
			index ++;
			reqTime = curMs;
			logd("grabByUser req sent!");
			return true;
		}
		return false;
	}

	@Override
	public void receive(String stamp, String sjson) {
		DatabaseHelper dh = mDm.getDatabaseHelper();
		if(dh == null)
			return;
		
		if(stamp.startsWith("CHECK_DEVICE_SETTINGS")){
			if(sjson != null){
				boolean update = false;
				String tid = "";
				try {
					JSONObject json = new JSONObject(sjson);
					int code = json.getInt("code");
					if(code == 200){
						String state = json.getString("state");
						JSONObject sd = json.getJSONObject("senddata");
						JSONObject recdata = json.getJSONObject("recdata");
						
						if((recdata != null) && state.equalsIgnoreCase("00")){
							tid = sd.getString("tid");
							ContentValues cv = new ContentValues();
							cv.put(DatabaseHelper.DEVSET_TID, tid);
							String model = recdata.getString("devicemodel");
							cv.put(DatabaseHelper.DEVSET_MODEL, model);
							String did = recdata.getString("deviceid");
							cv.put(DatabaseHelper.DEVSET_DID, did);
							String sn = recdata.getString("devicesn");
							cv.put(DatabaseHelper.DEVSET_SN, sn);
							String manu = recdata.getString("manufacturer");
							cv.put(DatabaseHelper.DEVSET_MANUFAC, manu);
							String sim = recdata.getString("isbindsim");
							if(sim.equals("1")){
								cv.put(DatabaseHelper.DEVSET_SIMBIND, "1");
							}else{
								cv.put(DatabaseHelper.DEVSET_SIMBIND, "0");
							}
							String mobile = recdata.getString("simno");
							cv.put(DatabaseHelper.DEVSET_MOBILE, mobile);
							String issue = recdata.getString("issuedtime");
							cv.put(DatabaseHelper.DEVSET_ISSUE, issue);
							String active = recdata.getString("isactdevice");
							if(active.equals("1")){
								cv.put(DatabaseHelper.DEVSET_ACTIVE, "1");
							}else{
								cv.put(DatabaseHelper.DEVSET_ACTIVE, "0");
							}
							
							upTime = System.currentTimeMillis();
							cv.put(DatabaseHelper.DEVSET_TIME, upTime);
							dh.updateItemInDevSetTable(tid, cv);
							
							dh.closeDB();
							update = true;
						}
					}
				}catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} 
				doNextRequest();
				Intent i = new Intent(DataManager.DATA_UPDATE_ACTION);
				i.putExtra("type",DataManager.F_DEVICE_SETTINGS);
				i.putExtra("state", update);
				i.putExtra("tid", tid);
				mApp.sendBroadcast(i);
			}
		}else if(stamp.startsWith("COMMIT_DEVICE_MOBILENUMBER")){
			if(sjson != null){
				String state = "af";
				int code = 400;
				String tid = "";
				try {
					JSONObject json = new JSONObject(sjson);
					code = json.getInt("code");
					JSONObject sd = json.getJSONObject("senddata");
					tid = sd.getString("tid");
					if(code == 200){
						state = json.getString("state");
						if(state.equalsIgnoreCase("00")){
							String[] arg = new String[1];
							arg[0] = tid;
							Cursor c = dh.queryDevSetTableDatas(arg);
							if(c.getCount() > 0){
								c.moveToNext();
								ContentValues cv = new ContentValues();
								cv.put(DatabaseHelper.DEVSET_TID, tid);
								
								String model = c.getString(c.getColumnIndex(DatabaseHelper.DEVSET_MODEL));
								cv.put(DatabaseHelper.DEVSET_MODEL, model);
								String did = c.getString(c.getColumnIndex(DatabaseHelper.DEVSET_DID));
								cv.put(DatabaseHelper.DEVSET_DID, did);
								String sn = c.getString(c.getColumnIndex(DatabaseHelper.DEVSET_SN));
								cv.put(DatabaseHelper.DEVSET_SN, sn);
								String manu = c.getString(c.getColumnIndex(DatabaseHelper.DEVSET_MANUFAC));
								cv.put(DatabaseHelper.DEVSET_MANUFAC, manu);
								String sim = c.getString(c.getColumnIndex(DatabaseHelper.DEVSET_SIMBIND));
								cv.put(DatabaseHelper.DEVSET_SIMBIND, sim);
								
								String mobile = sd.getString("simno");
								cv.put(DatabaseHelper.DEVSET_MOBILE, mobile);
								String issue = c.getString(c.getColumnIndex(DatabaseHelper.DEVSET_ISSUE));
								cv.put(DatabaseHelper.DEVSET_ISSUE, issue);
								String active = c.getString(c.getColumnIndex(DatabaseHelper.DEVSET_ACTIVE));
								cv.put(DatabaseHelper.DEVSET_ACTIVE, active);
								
								upTime = System.currentTimeMillis();
								cv.put(DatabaseHelper.DEVSET_TIME, upTime);
								dh.updateItemInDevSetTable(tid, cv);
							}
							
							c.close();
							dh.closeDB();
						}
					}
					
				}catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} 
				Intent i = new Intent(DataManager.DATA_COMMIT_RESULT);
				i.putExtra("type",DataManager.F_DEVICE_SETTINGS);
				i.putExtra("state", state);
				i.putExtra("cmd", "setmobile");
				i.putExtra("tid", tid);
				i.putExtra("code", code);
				mApp.sendBroadcast(i);
			}
		}
		
	}

	@Override
	public Object check(String[] arg) {
		DatabaseHelper dh = mDm.getDatabaseHelper();
		if(dh == null)
			return null;
		
		if((arg != null) && (arg.length>0)){
			Cursor c = dh.queryDevSetTableDatas(arg);
			if(c.getCount() > 0){
				int size = c.getCount();
				DEV_SET[] ret = new DEV_SET[size];
				for(int i=0; i< size; i++){
					c.moveToNext();
					ret[i] = new DEV_SET();
					ret[i].tid = c.getString(c.getColumnIndex(DatabaseHelper.DEVSET_TID));
					ret[i].did = c.getString(c.getColumnIndex(DatabaseHelper.DEVSET_DID));
					ret[i].model = c.getString(c.getColumnIndex(DatabaseHelper.DEVSET_MODEL));
					ret[i].sn = c.getString(c.getColumnIndex(DatabaseHelper.DEVSET_SN));
					ret[i].manufacture = c.getString(c.getColumnIndex(DatabaseHelper.DEVSET_MANUFAC));
					String sim = c.getString(c.getColumnIndex(DatabaseHelper.DEVSET_SIMBIND));
					ret[i].simBind = sim.equals("1")?true:false;
					ret[i].mobile = c.getString(c.getColumnIndex(DatabaseHelper.DEVSET_MOBILE));
					ret[i].issued = c.getString(c.getColumnIndex(DatabaseHelper.DEVSET_ISSUE));
					String act = c.getString(c.getColumnIndex(DatabaseHelper.DEVSET_ACTIVE));
					ret[i].active = act.equals("1")?true:false;
				
					ret[i].updateTime = c.getInt(c.getColumnIndex(DatabaseHelper.DEVSET_TIME));
				}
				c.close();
				dh.closeDB();
				return ret;
			}
		}
		return null;
	}

	@Override
	public boolean commit(Object data) {
		String uid = mApp.getUID();
		
		if((uid == null) || uid.isEmpty())
			return false;
			
		JSONObject json = (JSONObject)data;
		if(json == null)
			return false;
		
		try {
			String cmd = json.getString("cmd");
			String tid = json.getString("tid");
			String simno = json.getString("mobile");
			
			if(cmd.equalsIgnoreCase("setmobile")){
				Intent si = new Intent(NetService.COMMIT_DATA_ACTION);
				si.putExtra("sub_act", NetService.COMMIT_DEVICE_MOBILENUMBER);
				si.putExtra("uid", uid);
				si.putExtra("tid", tid);
				si.putExtra("simno", simno);
				
				Time t = new Time();
				t.setToNow();
				String stamp = "COMMIT_DEVICE_MOBILENUMBER" + t.toString(); 
				si.putExtra("stamp",stamp);
				mApp.addNetHandler(stamp,mDm.getBackGroundHandler());
				mApp.startService(si);
				
				return true;
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public void release() {
		// TODO Auto-generated method stub
		
	}
}
